package com.zmn.uac.config;

import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.config.ConfigType;
import com.alibaba.nacos.api.config.annotation.NacosConfigListener;
import com.zmn.uac.convert.LoggingLevelNacosConvert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Map;

/**
 * 动态日志处理类
 *
 * @author Rananquan
 * @since 2022年5月16日 18点38分
 */
@Configuration
@Slf4j
public class LoggingLevelConfiguration {
    @Resource
    private LoggingSystem loggingSystem;

    @Resource
    private Environment environment;

    @PostConstruct
    public void init() {
        String zmnLoggingLevel = environment.getProperty("zmn.logging.level", "INFO");
        loggingSystem.setLogLevel("com.zmn", LogLevel.valueOf(zmnLoggingLevel));
    }

    @NacosConfigListener(groupId = "${nacos.config.group}", dataId = "${nacos.config.data-id}",type = ConfigType.PROPERTIES,converter = LoggingLevelNacosConvert.class,timeout = Constants.CONFIG_LONG_POLL_TIMEOUT)
    public void onLoggingLevelChange(Map<String,LogLevel> logLevelMap) {
        logLevelMap.forEach((k,v)-> loggingSystem.setLogLevel(k,v));
    }
}
